//
//  HLOAuthViewController.swift
//  HLWeiBo
//
//  Created by jack on 15/12/7.
//  Copyright © 2015年 jack. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APPKEY = "15641238"
let WB_APPSECERT = "9e3aaa92110a57f8c82b8ec3644c0044"
let WB_REDIRECTURI = "http://www.itheima.com/"


class HLOAuthViewController: UIViewController ,UIWebViewDelegate{

    
    let hlWebView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECTURI)")
        hlWebView.loadRequest(NSURLRequest(URL: url!))
    }
    
    override func loadView() {
        
        view = hlWebView
        
        hlWebView.delegate = self
        
        title = "新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        
    }
    //dismiss控制器
   @objc private func dismiss(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //自动填充密码
    @objc private func autoFill(){
    
        let jsString = "document.getElementById('userId').value='15003126805';document.getElementById('passwd').value='sunhaoliang_122'"
        
        hlWebView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL?.absoluteString
        
        //如果不是以回调页开头,直接让webView继承加载
        if !url!.hasPrefix(WB_REDIRECTURI) {
            return true
        }
        
        //判断是否包含 'code=' 字样
        if let query = request.URL?.query where query.containsString("code=") {
        
        let code = query.substringFromIndex("code=".endIndex)
           print("请求码:\(code)")

            loadAccessToken(code)
        }else{
            close()
        }
        return false
    }
    //菊花
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true , completion: nil)
        
    }
    
    //加载数据
    private func loadAccessToken(code: String){
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id": WB_APPKEY,
            "client_secret": WB_APPSECERT,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECTURI]
        
        HMNetworkTools.shareTools.request(HMRequestMethod.POST, urlString: url, params: params) { (response, error) -> () in
            
            print(response)
            let account = HLUserAccount(dict: response as! [String: AnyObject])
            print(account)
        }
    }
    
    override var description: String {
        let keys = ["access_token","expires_in","remind_in","uid"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
}
